﻿using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tester
{
    public partial class FormTestcase : Form
    {
          private Dictionary<string, string> mCookies = new Dictionary<string, string>();//保存Cookie到字典中
    
        public FormTestcase()
        {
            InitializeComponent();
        }

        private void FormWebView2_Load(object sender, EventArgs e)
        {
            this.webView21.Source = new Uri("https://wenhui.link/authpage", System.UriKind.Absolute);
        }

        private void webView21_DocumentCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            var url = webView21.CoreWebView2.Source;
            var task = Task.Run(() =>
            {
                Thread.Sleep(2000);
            });
            task.GetAwaiter().OnCompleted(async () =>
            {
                var html = await webView21.CoreWebView2.ExecuteScriptAsync("document.getElementsByTagName('html')[0].outerHTML"); //第一次获取没法获取后端的数据
                html = Unicode2String(html);
                var obj = $"{{\"html\":{html}}}";
                //var b = JsonConvert.DeserializeObject<Doc>(obj);
                //File.WriteAllText("1.html", b.html);
            });
        }
        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <param name="source">经过Unicode编码的字符串</param>
        /// <returns>正常字符串</returns>
        static string Unicode2String(string source)
        {
            return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(source,
                x => Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)).ToString());
        }

        /// <summary>
        /// WebView2异步获取cookie
        /// </summary>
        /// <param name="url">与cookie关联的域名</param>
        private async void getCookie(string url)
        {
            List<CoreWebView2Cookie> cookieList = await webView21.CoreWebView2.CookieManager.GetCookiesAsync(url);
            mCookies.Clear();
            for (int i = 0; i < cookieList.Count; ++i)
            {
                CoreWebView2Cookie cookie = webView21.CoreWebView2.CookieManager.CreateCookieWithSystemNetCookie(cookieList[i].ToSystemNetCookie());
                mCookies.Add(cookie.Name, cookie.Value);
            }

        }

        /// <summary>
        /// 提取cookie中的一个字段；
        /// </summary>
        /// <param name="url">域名</param>
        /// <param name="key">关键字，如：web_session</param>
        /// <param name="t">延时（没用到）</param>
        /// <returns></returns>
        public string getCookieEx(string url, string key, int t)
        {
            getCookie(url);
            if (mCookies.ContainsKey(key))
            {
                string cookies = "";
                foreach (var cookie in mCookies)
                {
                    cookies += cookie.Key + "=" + cookie.Value + ";";
                }
                cookies = key + "=" + mCookies[key];
                return cookies;
            }


            return null;
        }

        private async void toolStripButtonGetHtml_Click(object sender, EventArgs e)
        {
            object obj = await webView21.CoreWebView2.ExecuteScriptAsync("document.body.innerHTML");//等一会儿获取HTML就能看到后端数据了
            //object obj = await webView21.CoreWebView2.ExecuteScriptAsync("document.body.innerText");//获取页面的文本
            //object obj = await webView21.CoreWebView2.ExecuteScriptAsync("$('.f3')[0].innerHTML");//jquery获取页面内容

            richTextBox1.Text = Unicode2String(obj.ToString());
        }

        private void toolStripButtonParseHtml_Click(object sender, EventArgs e)
        {

        }
    }
}
